# Uncomment this if you reference any of your controllers in activate
require_dependency 'application'

SALT = 'secured_pages_extension'

class SecurePagesExtension < Radiant::Extension
  version "0.1"
  description "Define which pages are secured and can only be visited by registered users"
  url "http://code.google.com/p/secure-pages/"
  
  define_routes do |map|
    # map.connect 'admin/website_users/:action', :controller => 'admin/website_user'
    map.website_user_index '/admin/website_users/', :controller => "admin/website_user", :action => "index"
    map.website_user_edit '/admin/website_users/edit/:id', :controller => "admin/website_user", :action => "edit"
    map.website_user_remove '/admin/website_users/remove/:id', :controller => "admin/website_user", :action => "remove"
    map.website_user_new '/admin/website_users/new', :controller => "admin/website_user", :action => "new"
    map.website_user_new_password '/admin/website_users/new_password/:id', :controller => "admin/website_user", :action => "new_password"
  end
  
  def activate
    LoginPage
    ChangePasswordPage
    LogoutPage
    
    SiteController.class_eval do
      
      session :disabled => false
      
      protected
      
      before_filter :check_secure_page, :only => :show_page
      
      # Redirects the user to a login page if the current page
      # is secured and the user is not logged in
      def check_secure_page
        secured_pages = @config['secure_pages.pages']
        return true if secured_pages.nil?
        if "/"+params[:url].to_s =~ Regexp.new(secured_pages) and !logged_in?
          login_page = Page.find_by_class_name("LoginPage")
          redirect_to "/"+login_page.slug if login_page.slug != params[:url].to_s
          return true
        else
          return true
        end
      end
      
      def logged_in?
        !session[:website_user_id].nil?
      end
      
    end
    
    admin.tabs.add "Website users", "/admin/website_users", :after => "Layouts", :visibility => [:all]
  end
  
  def deactivate
    admin.tabs.remove "Website users"
  end
  
end